package com.example.dytest.filter;

import cn.hutool.core.util.StrUtil;
import com.baomidou.dynamic.datasource.toolkit.DynamicDataSourceContextHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Slf4j
@WebFilter(filterName = "dsFilter", urlPatterns = {"/*"})
public class DynamicDatasourceFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        log.info("loading filter {}", filterConfig.getFilterName());
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        String tenant = request.getHeader("tenant");
        if (!StrUtil.hasBlank(tenant)){
            DynamicDataSourceContextHolder.push(tenant);
            filterChain.doFilter(servletRequest, servletResponse);
            DynamicDataSourceContextHolder.poll();
        }else {
            PrintWriter writer = response.getWriter();
            writer.write("tenant error!");
            writer.flush();
            writer.close();
            return;
        }
    }

    @Override
    public void destroy() {

    }
}
